package com.wd.jetpack.model.data

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.sqlite.db.SupportSQLiteDatabase
import com.wd.jetpack.model.ArticleBean
import com.wd.jetpack.model.data.dao.ArticleDao
import com.wd.jetpack.util.Logger
import com.wd.jetpack.util.SetHome

/**
 * 页面描述：AppDatabase
 *
 */
@Database(entities = [ArticleBean::class], version = 1)
abstract class AppDatabase : RoomDatabase() {

    abstract fun articleDao(): ArticleDao

    companion object {
        @Volatile
        private var INSTANCE: AppDatabase? = null

        fun getInstance(context: Context): AppDatabase =
                INSTANCE ?: synchronized(this) {
                    INSTANCE ?: buildDatabase(context).also { INSTANCE = it }
                }

        private fun buildDatabase(context: Context) =
                Room.databaseBuilder(
                        DatabaseContext(context, SetHome.roomFilePath()),
                        AppDatabase::class.java, DatabaseConstants.DB_NAME
                )
                        .addCallback(object : Callback() {
                            override fun onCreate(db: SupportSQLiteDatabase) {
                                super.onCreate(db)
                                Logger.i("创建数据库：${db.path}")
                            }

                            override fun onOpen(db: SupportSQLiteDatabase) {
                                super.onOpen(db)
                                Logger.i("查看栈信息：${db.isOpen}")
                            }
                        })
                        .allowMainThreadQueries()//允许在主线程查询数据
                        .fallbackToDestructiveMigration()//迁移数据库如果发生错误，将会重新创建数据库，而不是发生崩溃
                        .build()

    }

}